import React, { useState, useRef, useEffect } from 'react';
import { useTerminal } from '../hooks/useTerminal';
import { IonContent } from '@ionic/react';

export const Terminal: React.FC = () => {
  const { executeCommand, commandHistory, currentOutput, isLoading, getCurrentDirectory } = useTerminal();
  const [inputValue, setInputValue] = useState('');
  const terminalRef = useRef<HTMLDivElement>(null);
  
  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
    }
  }, [currentOutput]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!inputValue.trim()) return;
    
    await executeCommand(inputValue);
    setInputValue('');
  };

  return (
    <IonContent className="ion-padding">
      <div className="card w-full bg-base-100 shadow-xl">
        <div className="card-body">
          <h2 className="card-title text-primary">Terminal</h2>
          
          <div 
            ref={terminalRef}
            className="bg-neutral text-neutral-content p-4 rounded-lg h-96 overflow-y-auto font-mono"
          >
            {/* Command History and Output */}
            {commandHistory.map((cmd, index) => (
              <div key={index} className="mb-2">
                <div className="text-accent">$ {getCurrentDirectory()} &gt; {cmd}</div>
                {currentOutput && index === commandHistory.length - 1 && (
                  <div className="mt-1 text-info-content">
                    {currentOutput.error ? (
                      <span className="text-error">{currentOutput.error}</span>
                    ) : (
                      currentOutput.output
                    )}
                  </div>
                )}
              </div>
            ))}
            
            {/* Loading indicator */}
            {isLoading && (
              <div className="loading loading-dots loading-md text-primary"></div>
            )}
          </div>

          {/* Command Input */}
          <form onSubmit={handleSubmit} className="mt-4">
            <div className="join w-full">
              <div className="join-item flex items-center px-3 bg-base-200">
                $
              </div>
              <input
                type="text"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                className="input input-bordered join-item flex-1"
                placeholder="Enter command..."
                disabled={isLoading}
              />
              <button 
                type="submit" 
                className="btn btn-primary join-item"
                disabled={isLoading}
              >
                Execute
              </button>
            </div>
          </form>
        </div>
      </div>
    </IonContent>
  );
}; 